#include "ennemies.h"

/**
** @brief Add an element to the ennemies list in the object structrure
**
** @param Type of the element
** @param Object containing the ennemies list
*/
void     add_to_enn_list(e_enn type, s_object *object)
{
    s_enn_list *n;
    s_enn_list *l = object->enn_list;
    int *depart = object->src;

    n = malloc(sizeof (s_enn_list));

    n->id = (l) ? (l->id + 1) : 0;
    n->pos[0] = depart[0];
    n->pos[1] = depart[1];
    n->prev[0] = -1;
    n->prev[1] = -1;
    n->life = (l) ? (l->life + 2) : 2;
    n->pathfinding = get_astar(object);
    n->type = type;
    n->next = l;

    fprintf(stderr, "[+] Ennemy (id: %d)\n", n->id);

    object->enn_list = n;
}

/**
** @brief Print the ennemies list in the object
**
** @param Object containing the ennemies list
*/
void    print_enn_list(s_object *object)
{
    SDL_Rect pos;
    s_enn_list *l = NULL;
    int i = 1;

    l = object->enn_list;
    while (l)
    {
        if (l->pos[0] == object->dst[0] &&
            l->pos[1] == object->dst[1])
        {
            del_from_enn_list(l->id, &object->enn_list);
            object->life -= 1;
        }
        pos.x = l->pos[1] * IMG_X;
        pos.y = l->pos[0] * IMG_Y;

        SDL_BlitSurface(object->enn[E_LAMBDA], NULL, object->screen, &pos);
        l = l->next;
        i++;
    }
}

/**
** @brief remove the element which id is egal to id in the list
**
** @param x id of the element to remove
** @param l list of ennemies
*/
void    del_from_enn_list(int id, s_enn_list **l)
{
    s_enn_list *old = NULL;
    s_enn_list *curr = *l;

    while (curr && curr->next && curr->id != id)
    {
        old = curr;
        curr = curr->next;
    }

    if (curr == NULL)
    {
        fprintf(stderr, "[!] Ennemy deletion : Empty list\n");
        return;
    }

    if (curr->id != id)
    {
        fprintf(stderr, "[!] Ennemy deletion : Element not found\n");
        return;
    }
    fprintf(stderr, "[-] Ennemy (id: %d)\n", curr->id);
    if (old == NULL)
        *l = (*l)->next;
    else
        old->next = curr->next;

    free(curr);
}
